import abc
import core, contentRecog, ui
from contentRecog import recogUi
from ..bitmap import openMemoryImageFile
from ..utils import post
from ..wrapper import jsonData, notScreenCurtain, subthread
#自定义的内容识别类
class ContentRecognizer(contentRecog.ContentRecognizer):
    @abc.abstractmethod
    def onRecog(self, imgData):
        #imgData: 带有BMP文件头部信息的二进制数据
        raise NotImplementedError
    @abc.abstractmethod
    def onCancel(self):
        raise NotImplementedError
    #重写的NVDA识别方法
    #运行在子线程
    @subthread
    def recognize(self, pixels, imageInfo, onResult):
        #打开内存图像文件
        with openMemoryImageFile(imageInfo, pixels) as f:
            img=f.getvalue()
        #准备识别
        try:
            data = self.onRecog(img)
            result=contentRecog.LinesWordsResult(data, imageInfo)
            core.callLater(1, onResult, result) # 让回调函数放在主线程执行
        except Exception as e:
            ui.message(_('%s' % e))
    def cancel(self):
        #识别被取消
        self.onCancel()
    # 把 post 得到的数据转为 json
    @jsonData
    def post(self, url, data, headers = None):
        return post(url, data = data, headers = headers)
    #在非黑屏情况下启动识别
    @notScreenCurtain
    def start(self):
        recogUi.recognizeNavigatorObject(self)